const UserModel = require("../model/address");
const jwt = require("jsonwebtoken");
const {
    secret
} = require("../config");
const catchError = require("../utils/catchError");

let phone = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/

class Address {
    async addAdd(ctx) {
        let {
            username,
            realName,
            phoneNum,
            userAdd,
            isDef
        } = ctx.request.body;
        if (!username || !realName || !phoneNum || !userAdd) {
            return ctx.body = {
                code: 1,
                msg: "请填写完整信息",
            };
        }
        if (!phone.test(phoneNum)) {
            return ctx.body = {
                code: 1,
                msg: "请输入正确手机号码",
            };
        }
        let data = await UserModel.create({
            username,
            realName,
            phoneNum,
            userAdd,
            isDef
        });

        ctx.body = {
            code: 0,
            msg: "添加地址成功",
        };
    }

    async getAdd(ctx) {
        let { username } = ctx.request.body;
        let data = await UserModel.find({ username })

        ctx.body = {
            code: 0,
            msg: "获取地址成功",
            data:{
                ...data
            }
        };
    }

    async newAdd(ctx) {
        let { _id } = ctx.request.body;
        let allData = await UserModel.find({})
        // console.log(allData);
        let oldDef = await UserModel.updateOne({ isDef: true },{ isDef: false })
        let newDef = await UserModel.updateOne({ _id: _id },{ isDef: true })
        // await allData.forEach((e) => {
        //     if(e.isDef == true){
        //         let newDef = false
        //         let id = e._id
        //         console.log(id);
               

        //     }
        //     // console.log(e.isDef);
        // })
        // let data = await UserModel.findOne({ _id })
        // let upData = await UserModel.findByIdAndUpdate({_id},{newDef})
        ctx.body = {
            code: 0,
            msg: "获取地址成功",
        };
    }
}

module.exports = new Address();